package io.gitee.wiqer.medium;

import org.junit.Test;

import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicInteger;

public class SolutionNC88_FindKth {
    public int findKth(int[] a, int n, int k) {
        // write code here
        AtomicInteger result= new AtomicInteger(-1);
        ConcurrentSkipListMap<Integer,  Integer> source =new ConcurrentSkipListMap<Integer,  Integer>();
        for(Integer i:a){
            Integer r=source.get(i);
            if(r==null){
                r=0;
            }
            r++;
            source.put(i,r);
        }
        try {
            AtomicInteger skipCount= new AtomicInteger();
            source.forEach((key, value) -> {
                while (value-->0){
                    result.set(key);
                    skipCount.getAndIncrement();
                    if(skipCount.get()-1 ==n-k){
                        throw new IllegalArgumentException("");
                    }
                }

            });
        }catch (Exception e) {

        }

        return  result.get();
    }
    @Test
   public void test(){
        int[] a={10,10,9,9,8,7,5,6,4,3,4,2};
       System.out.println(findKth(a,12,3)) ;
        int[] a2={1332802,1177178,1514891,871248,753214,123866,1615405,328656,1540395,968891,1884022,252932,1034406,1455178,821713,486232,860175,1896237,852300,566715,1285209,1845742,883142,259266,520911,1844960,218188,1528217,332380,261485,1111670,16920,1249664,1199799,1959818,1546744,1904944,51047,1176397,190970,48715,349690,673887,1648782,1010556,1165786,937247,986578,798663};
        System.out.println(findKth(a2,49,24)) ;
        int[] a3={1,3,5,2,2};
        System.out.println(findKth(a3,5,3)) ;
   }
}
